package be.ipl.streams.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** 
 * Servlet implementation class Controleur
 * */
@SuppressWarnings("serial")
public class Controleur extends HttpServlet {

	/**
	 * @see HttpServlet#HttpServlet()
	 * */
	public Controleur() {
		super();
	}
	
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String url = request.getServletPath().substring(1);
		RequestDispatcher rd = getServletContext().getNamedDispatcher(url);
		if (url.isEmpty() || rd == null) {
			getServletContext().getNamedDispatcher("partie.html").forward(request, response);
		} else {
			rd.forward(request, response);
		}
	}
	
	public static Object sessionTest(HttpServlet servlet, HttpServletRequest request,
			HttpServletResponse response, String attribute, String target) throws ServletException, IOException {
		Object o = request.getSession().getAttribute(attribute);
		if (o != null) return o;
		
		RequestDispatcher rd = servlet.getServletContext().getNamedDispatcher(target);
		rd.forward(request, response);
		return null;
	}
	
	public static Object testConnected(HttpServlet servlet, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		return sessionTest(servlet, request, response, "player", "ConnectClass");
	}
	
	public static Object testGameJoined(HttpServlet servlet, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		return sessionTest(servlet, request, response, "game", "GameList");
	}
	
}
